
import requests
import re
import pygetwindow
import win32gui

def build_name_code_dict():
    # TODO: 对这个requests做错误处理和重试
    def by_jinshuyuan():
        response = requests.get('http://api.jinshuyuan.net/get_stk_dic')
        name_code_dict = {}
        datas = response.text
        datas = datas.split('<br/>')[1:]
        max_len = 0
        for data in datas:
            if data == '':
                continue
            else:
                data = data.split(',')
                id_, code, name = data
                max_len = len(name) if len(name) > max_len else max_len
                name_code_dict[name] = code.lower()
        return name_code_dict

    def by_dongfang():
        response = requests.get('http://quote.eastmoney.com/stock_list.html')
        a = re.compile('html">(.*)\(([0-9]{6})\)</a></li>')
        datas = a.findall(response.text)
        name_code_dict = {}
        for name, code in datas:
            name = name.encode(response.encoding).decode('GBK')
            name_code_dict[name] = code
        return name_code_dict

    print('**Main Moniter** build name code dict')
    name_code_dict = by_jinshuyuan()
    name_code_dict.update(by_dongfang())
    print(name_code_dict)
    return name_code_dict


def _build_main_windows():
    wins = pygetwindow.getWindowsWithTitle('大智慧 - [')
    main_win = 0
    if len(wins) == 1:
        main_win = wins[0]._hWnd
    else:
        for win in wins:
            title = win32gui.GetWindowText(win)
            if title.startswith('大智慧 - [') and title.endswith(']'):
                main_win = win._hWnd

    if main_win != 0:
        main_win = main_win
        return main_win
    else:
        return None

def get_code_by_main_window(main_win):
    """
    通过检测主窗口的[]中的名字是否在字典中，来获得代码
    :return:
    """
    name = win32gui.GetWindowText(main_win)
    stock_name = name.replace('大智慧 - [', '').replace(']', '')
    stock_name = stock_name.replace(' ', '')
    print('**Main Moniter**', stock_name)
    # print(stock_name, self.name_code_dict.get(stock_name, None))
    return stock_name

win = _build_main_windows()
name_code_dict = build_name_code_dict()
stock_name = get_code_by_main_window(win)
print(win, stock_name)
print(name_code_dict.get(stock_name))